# -*- coding: utf-8 -*-
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.asr.v20190614 import asr_client, models
import base64
import json
import json
import os
def speech_to_text(file_path):
    # 通过本地语音上传方式调用
    try:

        # 重要：<Your SecretId>、<Your SecretKey>需要替换成用户自己的账号信息
        # 请参考接口说明中的使用步骤1进行获取。
        secretId = "AKIDlMincGdjY6NN6ZmiNmulLegS4PTHo43l"
        secretKey = "SdYCZfU2JK4WidGdjY6NM5YkeHdjZHju"

        cred = credential.Credential(secretId, secretKey)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        clientProfile.signMethod = "TC3-HMAC-SHA256"
        client = asr_client.AsrClient(cred, "ap-shanghai", clientProfile)

        # 读取文件以及base64
        with open(file_path, 'rb') as f:
            data = f.read()
        base64Wav = base64.b64encode(data).decode()

        # 发送请求
        req = models.SentenceRecognitionRequest()
        #English tanslate add =>"EngSerViceType": "8k_en"
        params = {"ProjectId": 0, "SubServiceType": 2, "EngSerViceType": "8k", "SourceType": 1,
                  "VoiceFormat": "wav", "UsrAudioKey": "session-123", "Data": base64Wav}
        req._deserialize(params)
        resp = client.SentenceRecognition(req)
        #print(type(resp))
        #print()
        re=json.loads(resp.to_json_string())
        return re["Result"]
        # windows系统使用下面一行替换上面一行
        # print(resp.to_json_string().decode('UTF-8').encode('GBK') )
    except TencentCloudSDKException as err:
        print(err)

def trans(process_dir):
    #process_dir="./audio"
    result={}
    init=1
    try:
        for file in os.listdir(process_dir):
            filepath=os.path.join(process_dir,file)
            a = speech_to_text(filepath)
            print("translating NO.%s audio file...."%(init))
            init+=1
            result[file]=a
        json_str = json.dumps(result,ensure_ascii=False)
        with open('translation_result.json', 'w') as json_file:
            json_file.write(json_str)
    except:
        print(result)
        json_str = json.dumps(result,ensure_ascii=False)
        with open('translation_result_checkpoint.json', 'w') as json_file:
            json_file.write(json_str)


if __name__ == '__main__':
    process_dir = "./processed"
    trans(process_dir)